<?php
class App_Source_Structure_Validator extends Mozg_Property_Validator
{
	protected function ValidateName($value)
	{
		return strlen($value);
	}

	protected function ValidatePageType($value)
	{
		$pageTypes = Mozg_Cfg::Get('global/structure')->GetPageTypes();
		return isset($pageTypes[$value]);
	}

	protected function ValidateParentId($value)
	{
		if ($this->IsRoot())
		{
			if ($value != 0)
			{
	            $this->SetErrorMessage('parentId', Mozg_Lang::_('SUBCATEGORY_CANNOT_CONTAIN_ITS_PARENT_CATEGORY'));
	            return false;
			}

			return true;
		}

		$obj = $this->GetData();
		$structure = Mozg_Mapper::Get('Structure');

		$parentItem = $structure->GetOne(array('id' => $value));
    	if (!$parentItem)
    	{
    		$this->SetErrorMessage('parentId', Mozg_Lang::_('UNABLE_TO_FIND_PARENT_CATEGORY'));
    		return false;
    	}

    	if ($obj->GetId())
    	{
	        $subItems = $structure->GetList(array('parentId' => $obj->GetId(), 'levels' => 1000));
	        $subItems[$obj->GetId()] = $obj;
	        if (isset($subItems[$obj->GetParentId()]))
	        {
	            $this->SetErrorMessage('parentId', Mozg_Lang::_('SUBCATEGORY_CANNOT_CONTAIN_ITS_PARENT_CATEGORY'));
	            return false;
	        }
    	}

        return true;
	}

	protected function ValidateUrl($url)
	{
		if ($this->IsRoot())
		{
			return true;
		}

		if (!preg_match('/^[a-z_\-0-9]+$/uis', $url))
		{
			return false;
		}

		$obj = $this->GetData();
		$structure = Mozg_Mapper::Get('Structure');

		$parentItem = $structure->GetOne(array('id' => $obj->GetParentId()));
		$parentUrl = $parentItem->GetFullUrl();
		$fullUrl = $structure->CreateFullUrl($url, $parentUrl);

        $elem = $structure->GetOne(array('url' => $fullUrl));
        if ($elem && ($elem->GetId() != $obj->GetId()))
		{
			$this->SetErrorMessage('url', Mozg_Lang::_('THERE_IS_ANOTHER_CATEGORY_WITH_THE_SAME_URL_IN_THE_CURRENT_CATEGORY'));
			return false;
		}

		return true;
	}

	protected function IsRoot()
	{
		$rootElem = Mozg_Mapper::Get('Structure')->GetRoot();
		return (!$rootElem || ($this->GetData()->GetId() == $rootElem->GetId()));
	}
}